const router = require("express").Router();
const sql = require("../mysql");
const Admin = require("../mysql/collection/Admin");
const Role = require("../mysql/collection/Role");
const Menu = require("../mysql/collection/Menu");
const uuid = require("uuid");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const _ = require("lodash");

// const {
//   getMenuListWithRole,
//   getpermissionBtnListWithRole,
// } = require("../permissionUtil");
/**
 * @api {POST} /admin/admin/login 管理系统登录
 * @apiName PostLogin
 * @apiGroup Admin
 *
 * @apiParam { string } adminname 管理员账号 admin
 * @apiParam { string } password 密码 123456
 *
 * @apiSuccess {String} code 状态码.
 * @apiSuccess {String} message  描述
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200" || '10003' || '10005',
 *       "message": "登录成功" || 密码错误 ｜| 未注册,
 *     }
 */
router.post("/login", (req, res, next) => {
  let { adminname, password } = req.body;
  if (adminname === "" || password === "") {
    res.send({
      code: "66666",
      message: "想啥呢哥们，输入完整信息吧",
    });
  }
  console.log(adminname, password);
  sql.find(Admin, { adminname }, { __v: 0 }).then((data) => {
    if (data.length !== 0) {
      if (md5(password) === data[0].password) {
        console.log(data[0]);
        const accessToken = jwt.sign(
          { adminname, _id: data[0]._id, adminid: data[0].adminid, type: 'access' },
          "嗨购-admin",
          {
            expiresIn: "2h", // 2小时
          }
        );
        
        const refreshToken = jwt.sign(
          { adminid: data[0].adminid, type: 'refresh' },
          "嗨购-admin",
          {
            expiresIn: "30d", // 30天
          }
        );

        console.log(data[0]);
        res.status(200).send({
          code: "200",
          message: "登录成功",
          data: {
            adminname,
            adminid: data[0].adminid,
            token: accessToken,
            refreshToken,
            role: data[0].role,
            roleKeys: data[0].roleKeys,
            checkedkeys: data[0].checkedKeys,
            menuList: data[0].menuList,
            permissionList: data[0].permissionList,
            permissionBtnList: data[0].permissionBtnList,
          },
        });
      } else {
        res.status(200).send({
          code: "10003",
          message: "密码错误",
        });
      }
    } else {
      res.status(200).send({
        code: "10005",
        message: "未注册",
      });
    }
  });
});

//获取当前用户的IP
function getClientIp(req) {
  return (
    req.headers["x-forwarded-for"] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress ||
    ""
  );
}
/**
 * @api {post} /admin/admin/add 添加管理员
 * @apiName PostAddAdmin
 * @apiGroup Admin
 *
 * @apiParam { string } adminname
 * @apiParam { string } password
 * @apiParam { array } roleKeys  // 角色权限["ADMIN", "USER"]
 * @apiParam { string } role-废弃
 * @apiParam { string } checkedKeys-废弃
 * @apiParam { string } departmentId //部门id
 * @apiParam { string } departmentName//部门名称
 * @apiHeader { string } token
 *
 * @apiSuccess {String} code 状态码.
 * @apiSuccess {String} message  描述
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200" || '10004',
 *       "message": "添加管理员成功" || 该管理员已存在,
 *     }
 */

router.post("/add", (req, res, next) => {
  let insertData = req.body;

  let password = insertData.password;
  if (!insertData.adminname) {
    res.send({
      code: "10008",
      message: "管理员用户名不能为空",
    });
  } else {
    insertData.adminid = "admin_" + uuid.v4();
    insertData.password = md5(password);
    // let ip = getClientIp(req).match(/\d+.\d+.\d+.\d+/);
    //     let ip = req.ip.match(/\d+\.\d+\.\d+\.\d+/)
    // console.log(ip);
    //     insertData.ip = ip
    // insertData.checkedKeys =
    //   insertData.checkedKeys.length > 0 ? insertData.checkedKeys : [];

    insertData = {
      ...insertData,
      // menuList: getMenuListWithRole(insertData.role),
      // permissionList: getMenuListWithRole(insertData.role),
      // permissionBtnList: getpermissionBtnListWithRole(insertData.role),
    };
    // 判断有没有该管理员账号
    sql
      .find(Admin, { adminname: insertData.adminname }, { _id: 0, __v: 0 })
      .then((data) => {
        if (data.length === 0) {
          // 没有当前想要添加的管理员
          sql.insert(Admin, insertData).then(() => {
            res.send({
              code: "200",
              message: "添加管理员成功",
            });
          });
        } else {
          // 已有该管理员
          res.send({
            code: "10004",
            message: "该管理员已存在",
          });
        }
      });
  }
});
/**
 * @api {post} /admin/admin/delete 删除管理员
 * @apiName PostDeleteAdmin
 * @apiGroup Admin
 *
 * @apiParam { string } adminid
 *
 * @apiHeader { string } token
 *
 * @apiSuccess {String} code 状态码.
 * @apiSuccess {String} message  描述
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200",
 *       "message": "删除管理员"
 *     }
 */
router.post("/delete", (req, res, next) => {
  const { adminid } = req.body;
  sql.delete(Admin, { adminid }).then(() => {
    res.send({
      code: "200",
      message: "删除管理员",
    });
  });
});
/**
 * @api {get} /admin/admin/detail 获取管理员信息
 * @apiName GetDetailAdmin
 * @apiGroup Admin
 *
 * @apiParam { string } adminid
 *
 * @apiHeader { string } token
 *
 * @apiSuccess {String} code 状态码.
 * @apiSuccess {String} message  描述
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200",
 *       "message": "获取管理员信息" ,
 *        data
 *     }
 */
router.get("/detail", async (req, res, next) => {
  const { adminid } = req.query;
  const data = await sql.find(
    Admin,
    { adminid },
    { _id: 0, __v: 0, password: 0 }
  );
  if (data.length > 0) {
    const adminData = data[0];
    const menuList = await getMenuListWithRoleKeys(adminData.roleKeys);
    res.status(200).send({
      code: "200",
      message: "获取管理员信息",
      data: {
        ...adminData._doc,
        menuList: _.uniqBy(menuList, "_id"),
        permissionList: _.uniqBy(menuList, "_id"),
      },
    });
  } else {
    res.status(200).send({
      code: "404",
      message: "未找到管理员信息",
    });
  }
});
/**
 * @api {patch} /admin/admin/update/:adminid 修改管理员信息
 * @apiName PostAdminUpdate
 * @apiGroup Admin
 *
 * @apiHeader { string } token
 * @apiParam { string } adminid
 * @apiBody { string } adminname
 * @apiBody { string } password
 * @apiBody { string } roleKeys
 *
 * @apiSuccess {String} code 状态码.
 * @apiSuccess {String} message  描述
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200",
 *
 *       "message": "修改管理员信息"
 *     }
 */
router.patch("/update/:adminid", (req, res, next) => {
  console.log(req.body);
  let updateData = req.body;
  // updateData.role = updateData.role;
  if (updateData.adminname === "admin") {
    res.status(200).send({
      code: "200",
      message: "你想翻天吗",
    });
  } else {
    if (updateData.password.length >= 0) {
      // updateData.password = md5(updateData.password);
      updateData.password = md5(updateData.password);
    }
    sql
      .update(
        Admin,
        { adminid: req.params.adminid },
        {
          $set: {
            // adminname: updateData.adminname,
            // role: updateData.role,
            // checkedKeys: updateData.checkedKeys,
            ...updateData,
            // password
          },
        }
      )
      .then(() => {
        res.send({
          code: "200",
          message: "修改管理员权限成功",
        });
      });
  }
});
/**
 * @api {get} /admin/admin/list 管理员列表
 * @apiName PostAdminList
 * @apiGroup Admin
 *
 * @apiHeader { string } token
 *
 * @apiSuccess {String} code 状态码.
 * @apiSuccess {String} message  描述
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200",
 *       "message": "管理员列表"
 *     }
 */
router.get("/list", async (req, res, next) => {
  // 查找adin表数据，排除__v和_id字段，排除password字段
  Admin.find({}, { __v: 0, _id: 0, password: 0 })
    .populate("departmentId")
    .then(async (data) => {
      // 遍历admin表数据，更新menuList和permissionList字段
      for (let i = 0; i < data.length; i++) {
        let arr = await getMenuListWithRoleKeys(data[i].roleKeys);
        arr = _.uniqBy(arr, "_id");
        data[i].menuList = arr;
        data[i].permissionList = arr;
      }
      res.send({
        code: "200",
        message: "管理员列表",
        data,
      });
    });

  // sql.find(Admin, {}, { __v: 0 ,_id:0,password:0})
  // .then(async (data) => {
  // const index = data.findIndex((item) => item.adminname === "admin");
  // data.splice(index, 1);
  // data.map((item) => {
  //   item.menuList = getMenuListWithRoleKeys(item.roleKeys);
  //   item.permissionList = getMenuListWithRoleKeys(item.roleKeys);
  // });
  // for(let i=0;i<data.length;i++){
  //   let arr = await getMenuListWithRoleKeys(data[i].roleKeys);
  //   arr = _.uniqBy(arr, '_id');
  //   data[i].menuList =  arr
  //   data[i].permissionList = arr
  // }
  // res.send({
  //   code: "200",
  //   message: "管理员列表",
  //   data,
  // });

  // });
});

// 根据角色roleKeys获取菜单列表
async function getMenuListWithRoleKeys(roleKeys) {
  // let roleKeys = ['ADMIN',"SUPER_ADMIN888"]
  let menuList = [];
  for (let i = 0; i < roleKeys.length; i++) {
    //根据roleKey获取role数据，然后获取roleMenuArr
    let data = await sql.find(Role, { roleKey: roleKeys[i] });
    // console.log(data); //[ { roleKey: 'ADMIN', roleMenuArr: [Array] } ]
    if (data.length !== 0) {
      for (let j = 0; j < data.length; j++) {
        // 根据roleMenuArr获取菜单数据

        for (let k = 0; k < data[j].roleMenuArr.length; k++) {
          // 遍历roleMenuArr，获取角色的每一条菜单数据，更新菜单数据
          let menu = data[j].roleMenuArr[k];
          // 更新menu数据（用户可能修改）
          let newMenu = await sql.find(
            Menu,
            { _id: menu._id },
            { _id: 0, __v: 0 }
          );
          if (newMenu.length !== 0) {
            menu = { ...menu, ...newMenu[0] };
          }
          menuList.push(menu);
        }
        // menuList.push(...data[j].roleMenuArr)
      }
    }
  }
  // roleKeys.forEach(async (item) => {
  //   let r = await sql.find(Role, {roleKey:item})
  //   console.log(r);
  //   if(r.length!==0){
  //     menuList = [...menuList,...r[0].roleMenuArr]
  //   }
  //   // menuList = [...menuList, ...getMenuList(item)];
  // });

  return menuList;
}

/**
 * @api {post} /admin/admin/refresh-token 刷新管理员token
 * @apiName PostAdminRefreshToken
 * @apiGroup Admin
 * @apiDescription 使用refreshToken获取新的accessToken
 *
 * @apiParam {String} refreshToken 刷新token
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '10020',
 *    message: 'refreshToken无效或已过期'
 *  }
 *  {
 *    code: '200',
 *    message: 'token刷新成功',
 *    data: {
 *      accessToken,
 *      refreshToken,
 *      adminid
 *    }
 *  }
 */
router.post("/refresh-token", (req, res, next) => {
  const { refreshToken } = req.body;
  
  if (!refreshToken) {
    return res.send({
      code: "10020",
      message: "refreshToken不能为空",
    });
  }

  // 验证refreshToken的有效性
  jwt.verify(refreshToken, "嗨购-admin", (err, decoded) => {
    if (err || decoded.type !== 'refresh') {
      return res.send({
        code: "10020",
        message: "refreshToken无效或已过期",
      });
    }

    // 查找管理员信息
    sql.find(Admin, { adminid: decoded.adminid }, { __v: 0 }).then((adminData) => {
      if (adminData.length === 0) {
        return res.send({
          code: "10005",
          message: "管理员不存在",
        });
      }

      const admin = adminData[0];
      // 生成新的accessToken和refreshToken
      const newAccessToken = jwt.sign(
        { 
          adminname: admin.adminname, 
          _id: admin._id, 
          adminid: admin.adminid,
          type: 'access' 
        },
        "嗨购-admin",
        {
          expiresIn: "2h", // 2小时
        }
      );
      
      const newRefreshToken = jwt.sign(
        { adminid: admin.adminid, type: 'refresh' },
        "嗨购-admin",
        {
          expiresIn: "30d", // 30天
        }
      );

      res.send({
        code: "200",
        message: "token刷新成功",
        data: {
          adminname: admin.adminname,
          adminid: admin.adminid,
          token: newAccessToken,
          refreshToken: newRefreshToken,
          role: admin.role,
          roleKeys: admin.roleKeys,
          checkedkeys: admin.checkedKeys,
          menuList: admin.menuList,
          permissionList: admin.permissionList,
          permissionBtnList: admin.permissionBtnList,
        },
      });
    }).catch((error) => {
      res.send({
        code: "10021",
        message: "服务器错误",
      });
    });
  });
});

module.exports = router;
